package com.open.server;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.open.bean.vo.OpenVo;
import com.tencentcloudapi.asr.v20190614.AsrClient;
import com.tencentcloudapi.asr.v20190614.models.SentenceRecognitionRequest;
import com.tencentcloudapi.asr.v20190614.models.SentenceRecognitionResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author tanyongpeng
 * <p>语音转文字服务</p>
 **/
@Component
@Slf4j
public class VoiceServer {


    @Value("${tencentcloudapi.secretId}")
    private String secretId;
    @Value("${tencentcloudapi.secretKey}")
    private String secretKey;
    @Value("${tencentcloudapi.voice.endpoint}")
    private String endpoint;

    /**
     * @doc 官方文档；https://cloud.tencent.com/document/product/1093/35646
     * @param mp3Base64 声音base64
     * @param dataLength 长度
     * @param viceType 声音类型 16k_zh
     * @return
     */
    public OpenVo voice(String mp3Base64,Long dataLength,String viceType){
        System.out.println(mp3Base64);
        System.out.println("dataLength = " + dataLength);
        OpenVo openVo = new OpenVo();
        try{
            Credential cred = new Credential(secretId, secretKey);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(endpoint);
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            AsrClient client = new AsrClient(cred, "", clientProfile);
            SentenceRecognitionRequest req = new SentenceRecognitionRequest();
            req.setProjectId(0L);
            req.setSubServiceType(2L);
            req.setEngSerViceType(viceType);
            req.setSourceType(1L);
            req.setVoiceFormat("mp3");
            req.setUsrAudioKey("123");
            req.setData(mp3Base64);
            req.setDataLen(dataLength);
            SentenceRecognitionResponse resp = client.SentenceRecognition(req);
            log.info("结果==========={}",JSONUtil.toJsonStr(resp));
            openVo.setMsg(resp.getResult());
            openVo.setState(true);
            return openVo;
        } catch (TencentCloudSDKException e) {
            openVo.setMsg(e.getMessage());
            openVo.setState(true);
            e.printStackTrace();
            return openVo;
        }
    }

}
